<template>
  <div class="login-container">
    <h2>Login</h2>
    <form @submit.prevent="submitForm">
      <label>
        Username:
        <input v-model="userName" type="" required />
      </label>
      <label>
        Password:
        <input v-model="userPassword" type="password" required />
      </label>
      <button type="submit">Submit</button>
    </form>
  </div>

</template>

<script setup lang="ts" name="Login">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const userName = ref('');
const userPassword = ref('');
const router = useRouter(); // 获取路由实例

const submitForm = async () => {
  try {
    const response = await axios.post('http://localhost:8080/api/users/login', {
      'username': userName.value,
      'password': userPassword.value,
    });

    if (response.status === 200) {
      // 登录成功，保存token
      localStorage.setItem('token', response.data.token);
      axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;
      // 跳转到首页
      router.push('/home'); // 使用router实例进行跳转
    }
  } catch (error) {
    console.error(error);
      // 未授权，跳转到注册页面
      router.push('/register'); // 使用router实例进行跳转

  }
};
const hideHeader = ref(false);
</script>

<style scoped>
.login-container {
  width: 300px;
  margin: 0 auto;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.login-container form {
  display: flex;
  flex-direction: column;
}

.login-container form label {
  margin-bottom: 10px;
}

.login-container form input {
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
}

.login-container form button {
  padding: 10px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.login-container form button:hover {
  background-color: #0056b3;
}
</style>
